package thuai.ccf2013.query;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import thuai.ccf2013.driver.Driver;
import thuai.ccf2013.util.MyFileReader;
import thuai.ccf2013.util.MyFileWriter;

public class SearchEngine {
	
	public static Map<String, String> parseResult() {
		Map<String, String> map = new HashMap<String, String>();
		MyFileReader mfr = new MyFileReader(Driver.DATADIR + "baiduserpparse2.txt");
		String temp = null;
		while ((temp = mfr.getNextLine()) != null) {
			if (temp.contains("百度百科")) {
				String[] seg = temp.split("::");
				if (seg.length != 2) {
					continue;
				}
				
//				System.out.println(seg[0] + ":" + seg[1]);
				String target = seg[1].substring(0, seg[1].indexOf("_"));
//				System.out.println(seg[0] + ":" + target);
				map.put(seg[0], target);
			}
		}
		mfr.close();
		MyFileWriter mfw = new MyFileWriter(Driver.DATADIR + "mapper.txt", true);
		for (String key : map.keySet()) {
			mfw.write(key + "\t" + map.get(key) + "\n");
		}
		return map;
	}
	
	@Deprecated
	public static Map<String, String> parseResult(String dir) {
		Map<String, String> map = new HashMap<String, String>();
		
		File f = new File(dir);
		String[] filelist = f.list();
		if (!dir.endsWith("\\")) {
			dir += "\\";
		}
		MyFileWriter mfw = new MyFileWriter(Driver.DATADIR + "mapper.txt", true);
		StringBuilder pool = new StringBuilder();
		for (String filename : filelist) {
			String keyword = filename.substring(0, filename.indexOf("."));
			MyFileReader mfr = new MyFileReader(dir + filename);
			String temp = null;
			Pattern pat = Pattern.compile("<em>(.*)<.em>(.*)");
			String mid = "<em>" + keyword + "</em>";
			while ((temp = mfr.getNextLine()) != null) {
				pool.append(temp.trim());
			}
			int begin = 0;
			temp = pool.toString();
			while ((begin = temp.indexOf(mid, begin + 1)) >= 0) {
				int end = begin + 60 < temp.length() ? begin + 60 : temp.length();
				String target = temp.substring(begin, end);
//				mfw.write(target + "\n");
				if (target.contains("_百度百科")) {
					Matcher matcher = pat.matcher(target);
					if (matcher.find()) {
						target = matcher.group(1) + matcher.group(2);
						target = target.substring(0, target.indexOf("<"));
						map.put(keyword, target);
//						System.out.println(keyword + ":" + target);
						mfw.write(keyword + ":" + target + "\n");
					}
				}
			}
		}
		mfw.close();
		
		return map;
	}
	
}
